module Payers
  class VerificationCodesController < ApplicationController

    REGISTER_SMS_TEMPLATE = <<-SMS.strip.freeze
      您注册用的短信验证码是 %s
    SMS

    RESET_PASSWORD_SMS_TEMPLATE = <<-SMS.strip.freeze
      您重置密码用的短信验证码是 %s
    SMS

    def create_or_update
      verification_code = VerificationCode.find_or_initialize_by(params.permit(:mobile, :usage))
      verification_code.code = '%06d' % rand(1_000_000)
      verification_code.expires_at = 30.minutes.from_now

      if verification_code.save
        template = self.class.const_get(:"#{params[:usage].upcase}_SMS_TEMPLATE")
        content = template % verification_code.code
        SmsClient.send(params[:mobile], content)
        Rails.env.production? ? head(:no_content) : render(json: verification_code)
      else
        render json: verification_code.errors, status: :unprocessable_entity
      end
    end

  end
end
